<template>
  <view v-if="!hasLogin" class="empty need_login">
      <u-empty text="未登录" mode="permission">
        <button size="mini" slot="bottom" class="go-to-login" @click="gotoPath('/pages/login/index?from=cart',false)">请先登录</button>
      </u-empty>
  </view>
  <view v-else class="container p-bottom">
    <view class="cart-list">
      <view v-if="list.length>0">
        <view class="cart-edit-wrap dis-flex flex-x-end">
          <text v-if="action === 'complete'" @tap.stop.prevent="switchAction" class="f-30" data-action="edit">编辑
          </text>
          <text v-if="action === 'edit'" @tap.stop.prevent="switchAction" class="f-30" data-action="complete">完成
          </text>
        </view>
        <view v-for="(item, index) in list" :key="index">
          <view class="dish-item dis-flex flex-y-center" :data-index="index" :style="item.txtStyle">
            <!-- 选择框 -->
            <view class="dish-item-radio" @tap="radioChecked" :data-index="index">
              <label class="radio">
                <radio :checked="item.checked" color="#ff495e"></radio>
              </label>
            </view>
            <view class="dish-item-wrp dis-flex flex-box">
              <!-- 商品图片 -->
              <navigator hover-class="none" :url="'/pages/goods/detail?item_id=' + item.goods_id">
                <view class="dish-item-pic">
                  <image mode="aspectFill" class="image" :src="item.goods_image"></image>
                </view>
              </navigator>
              <!-- 商品信息 -->
              <view class="dish-item-info flex-box">
                <navigator hover-class="none" :url="'/pages/goods/detail?item_id=' + item.goods_id">
                  <view class="goods-name">
                    <text class="twolist-hidden f-30 col-3">{{ item.goods_name }}</text>
                  </view>
                  <view class="goods-attr dis-flex">
                    <text class="col-7 f-24">{{ item.spec_name }}</text>
                  </view>
                </navigator>
                <view class="dis-flex flex-x-between m-top20">
                  <!-- 商品价格 -->
                  <view class="wx-goods_price dis-flex flex-y-center">
                    <text class="dish-item-money">￥{{ item.goods_price }}</text>
                  </view>
                  <!-- 数量选择器 -->
                  <view class="selectNumber">
                    <button
                        @tap="minusCount"
                        :class="'default ' + (item.goods_num > 1 ? '' : ' default-active')"
                        :data-index="index"
                        :data-sku-id="item.spec_id"
                        type="default"
                    >
                      -
                    </button>
                    <input @input="importFun" :disabled="true" type="number" :value="item.goods_num"/>
                    <button @tap="addCount" class="default" :data-index="index" :data-sku-id="item.spec_id"
                            type="default">+
                    </button>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <!-- 底部操作栏 -->
        <view class="cart-tab-wrp">
          <view class="cart-item-total cart-tab-item dis-flex flex-y-center">
            <view class="checked-all">
              <label @tap.stop.prevent="radioCheckedAll" class="radio dis-flex flex-y-center">
                <radio class="margin-right: 10rpx;" :checked="checkedAll" color="#ff495e"></radio>
                <text class="f-28">全选</text>
              </label>
            </view>
            <view v-if="action === 'complete'" class="cart-item-total-price dis-flex">
              <text class="f-28 col-m">合计：￥{{ cartTotalPrice }}</text>
            </view>
          </view>
          <view class="cart-tab-item">
            <view v-if="action === 'complete'" @tap="submit" class="cart-tab-item-btn">去结算</view>
            <view v-if="action === 'edit'" @tap="deleteHandle" class="cart-tab-item-btn">删除</view>
          </view>
        </view>
      </view>
      <view v-else>
        <view class="bsshop-notcont">
          <text class="iconfont icon-wushuju"></text>
          <text class="cont">亲，购物车还没有商品哦</text>
          <view @tap="goShopping" class="cart-btn-min">去购物</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import cart_api from "@/common/cart_api";

export default {
  data() {
    return {
      list:[],
      action: 'complete',
      checkedAll: false,
      // 商品总价格
      cartTotalPrice: '0.00',
      order_total_price: ''
    };
  },

  onLoad: function (options) {

  },
  onPullDownRefresh() {
    this.list = []
    this.getCartList();
  },


  onShow: function () {
    this.getCartList();
  },
  methods: {
    /**
     * 获取购物车列表
     */
    getCartList: function () {
      let that = this;
      cart_api.list().then(res => {
        if (res.code !== 0) {
          this.$u.toast(res.msg)
          return
        }
        that.setData({
          list: res.data.list,
          order_total_price: res.data.order_total_price,
          action: 'complete',
          checkedAll: false,
          cartTotalPrice: '0.00'
        });
      }).finally(() => {
        uni.stopPullDownRefresh();
      });
    },

    /**
     * 选择框选中
     */
    radioChecked: function (e) {
      let that = this;
      let index = e.currentTarget.dataset.index;
      let checked = !that.list[index].checked;
      that.setData({
            ['list[' + index + '].checked']: checked
          },
          function () {
            // 更新购物车已选商品总价格
            that.updateTotalPrice();
          }
      );
    },

    /**
     * 选择框全选
     */
    radioCheckedAll: function (e) {
      let that = this;
      let goodsList = this.list;
      goodsList.forEach(function (item) {
        item.checked = !that.checkedAll;
      });
      that.setData({
            list: goodsList, checkedAll: !that.checkedAll
          },
          function () {
            // 更新购物车已选商品总价格
            that.updateTotalPrice();
          }
      );
    },

    /**
     * 切换编辑/完成
     */
    switchAction: function (e) {
      let that = this;
      that.setData({
        action: e.currentTarget.dataset.action
      });
    },

    /**
     * 删除商品
     */
    deleteHandle: function () {
      let that = this;
      let cartIds = that.getCheckedIds();
      if (!cartIds.length) {
        that.show_msg('您还没有选择商品');
        return false;
      }
      uni.showModal({
        title: '',
        content: '您确定要移除选择的商品吗?',
        success: function (e) {
          if (!e.confirm) {
            return false
          }
          cart_api.remove({ids: cartIds})
              .then(res => {
                that.$u.toast(res.msg)
                if (res.code === 0) {
                  that.getCartList();
                }
              })
        }
      });
    },

    /**
     * 获取已选中的商品
     */
    getCheckedIds: function () {
      let arrIds = [];
      this.list.forEach(function (item) {
        if (item.checked === true) {
          arrIds.push(item.id)
        }
      });
      return arrIds;
    },

    /**
     * 更新购物车已选商品总价格
     */
    updateTotalPrice: function () {
      let that = this;
      let cartTotalPrice = 0;
      that.list.forEach(function (item) {
        if (item.checked === true) {
          cartTotalPrice = that.mathadd(cartTotalPrice, item.total_price);
        }
      });
      that.setData({
        cartTotalPrice: Number(cartTotalPrice).toFixed(2)
      });
    },

    /**
     * 递增指定的商品数量
     */
    addCount: function (e) {
      let that = this;
      let index = e.currentTarget.dataset.index;
      let spec_id = e.currentTarget.dataset.skuId;
      let goods = that.list[index]; // order_total_price = _this.data.order_total_price;
      // 后端同步更新
      uni.showLoading({
        title: '加载中',
        mask: true
      });
      cart_api.action({
        item_id: goods.goods_id,
        goods_num: goods.goods_num + 1,
        spec_id: spec_id
      })
          .then(res => {
            if (res.code !== 0) {
              this.$u.toast(res.msg)
              return
            }
            // 商品数量
            goods.goods_num++;
            // 商品总价格
            goods.total_price = that.mathadd(goods.total_price, goods.goods_price);
            // 更新商品信息
            that.setData({['list[' + index + ']']: goods}, () => {
              that.updateTotalPrice();
            });
          }).finally(() => {
        uni.hideLoading();
      })
    },

    /**
     * 递减指定的商品数量
     */
    minusCount: function (e) {
      let that = this;
      let index = e.currentTarget.dataset.index;
      let spec_id = e.currentTarget.dataset.skuId;
      let goods = that.list[index]; // order_total_price = _this.data.order_total_price;
      console.log(goods);
      if (goods.goods_num > 1) {
        // 后端同步更新
        uni.showLoading({
          title: '加载中',
          mask: true
        });
        cart_api.action({
          item_id: goods.goods_id,
          spec_id: spec_id,
          goods_num: goods.goods_num - 1,
        })
            .then(res => {
              if (res.code !== 0) {
                this.$u.toast(res.msg)
                return
              }

              // 商品数量
              goods.goods_num--;
              if (goods.goods_num > 0) {
                // 商品总价格
                goods.total_price = that.mathsub(goods.total_price, goods.goods_price);
                // 更新商品信息
                that.setData({['list[' + index + ']']: goods}, () => {
                      that.updateTotalPrice()
                    }
                );
              }
            }).finally(() => {
          uni.hideLoading();
        })
      }
    },

    /**
     * 购物车结算
     */
    submit: function () {
      let that = this;
      let cartIds = that.getCheckedIds();
      if (!cartIds.length) {
        this.$u.toast('请选择需要结算的商品')
        return false;
      }
      uni.navigateTo({
        url: '/pages/cart/checkout?order_type=cart&cart_ids=' + cartIds
      });
    },

    /**
     * 加法
     */
    mathadd: function (arg1, arg2) {
      return (Number(arg1) + Number(arg2)).toFixed(2);
    },

    /**
     * 减法
     */
    mathsub: function (arg1, arg2) {
      return (Number(arg1) - Number(arg2)).toFixed(2);
    },

    /**
     * 去购物
     */
    goShopping: function () {
      uni.switchTab({
        url: '/pages/index/index'
      });
    },


    importFun() {
      console.log('占位：函数 import 未声明');
    }
  }
};
</script>
<style lang="scss">
@import 'index.scss';
</style>
